package com.example.spring.mono.config;

import org.springframework.lang.Nullable;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.client.reactive.ReactiveRestClients;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.repository.config.EnableReactiveElasticsearchRepositories;

@Configuration
@EnableReactiveElasticsearchRepositories(basePackages = "com.example.spring.mono.repository")
public class ReactiveElasticsearchConfig {
    @Bean
    public ClientConfiguration clientConfiguration() {
        return ClientConfiguration.builder()
               // .connectedTo("localhost:9200","node2_ip:9200","node3_ip:9200")
               .connectedTo("localhost:9200")
                .build();
    }
    @Bean
    public ReactiveElasticsearchClient reactiveElasticsearchClient(ClientConfiguration clientConfiguration) {
        return ReactiveRestClients.create(clientConfiguration);
    }
    //配置ReactiveElasticsearchTemplate模板，这里为了方便就直接复制AbstractReactiveElasticsearchConfiguration默认的
    //如果是继承AbstractReactiveElasticsearchConfiguration的方式可以不用配置，如果要配置就重写下列方法
    @Bean
    public ReactiveElasticsearchOperations reactiveElasticsearchTemplate(ElasticsearchConverter elasticsearchConverter, ReactiveElasticsearchClient reactiveElasticsearchClient) {
        ReactiveElasticsearchTemplate template = new ReactiveElasticsearchTemplate(reactiveElasticsearchClient, elasticsearchConverter);
        template.setIndicesOptions(this.indicesOptions());
        template.setRefreshPolicy(this.refreshPolicy());
        return template;
    }

    @Nullable
    protected RefreshPolicy refreshPolicy() {
        return null;
    }

    @Nullable
    protected IndicesOptions indicesOptions() {
        return IndicesOptions.strictExpandOpenAndForbidClosed();
    }

}
